package wh.jh.dubbo.server.api;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import wh.jh.dubbo.server.pojo.Voice;

import java.util.List;

@Service(version = "1.0.0")
public class VoiceApiImpl implements VoiceApi {
    @Autowired
    private MongoTemplate mongoTemplate;
    /**
     * @author  官文皓
     * @create  2021/6/1
     * @desc    上传语音
     **/
    @Override
    public Boolean saveVoice(Voice voice) {
        this.mongoTemplate.save(voice);
        return true;
    }

    /**
     * @author  官文皓
     * @create  2021/6/1
     * @desc    随机获取语音
     **/
    @Override
    public Voice getVoice(Long userId) {
        Query query = Query.query(Criteria.where("userId").ne(userId));
        List<Voice> voices = this.mongoTemplate.find(query, Voice.class);
        int count = voices.size();
        Voice voice = new Voice();
        if (ObjectUtil.isEmpty(voices)) {
            return voice;
        }
        int index = (int) Math.random()* count;
        voice = voices.get(index);
        Query deleteQuery = new Query(Criteria.where("_id").is(voice.getId()));
        mongoTemplate.remove(deleteQuery,Voice.class);// 删除
        return voice;
    }
}
